package com.junzhiit.nengji.cms.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.bainaeco.framework.util.DateUtil;
import com.junzhiit.nengji.bo.GoodsRefundBO;
import com.junzhiit.nengji.bo.SendPhoneMessageBO;
import com.junzhiit.nengji.cms.service.GoodsRefundService;
import com.junzhiit.nengji.cms.web.exception.LimitControlException;
import com.junzhiit.nengji.cms.web.exception.MobilePhoneNotFoundException;
import com.junzhiit.nengji.cms.web.exception.SendSMSFaileException;
import com.junzhiit.nengji.cms.web.exception.ShopNotFoundException;
import com.junzhiit.nengji.cms.web.util.ViewObjectUtil;
import com.junzhiit.nengji.cms.web.util.aliyun.SmsUtil;
import com.junzhiit.nengji.cms.web.util.aliyun.bean.SMSParams;
import com.junzhiit.nengji.cms.web.vo.DataTablesParamVO;
import com.junzhiit.nengji.cms.web.vo.GoodsRefundVO;
import com.junzhiit.nengji.cms.web.vo.ResultVO;
import com.junzhiit.nengji.cms.web.vo.SystemUserSessionVO;
import com.junzhiit.nengji.dao.GoodsRefundDAO;
import com.junzhiit.nengji.dao.OrdersGoodsDAO;
import com.junzhiit.nengji.dao.ShopDAO;
import com.junzhiit.nengji.dao.UserDAO;
import com.junzhiit.nengji.dao.cache.SystemUserCacheDAO;
import com.junzhiit.nengji.dao.util.DIYKey;
import com.junzhiit.nengji.model.GoodsRefund;
import com.junzhiit.nengji.model.OrdersGoods;
import com.junzhiit.nengji.model.Shop;
import com.junzhiit.nengji.model.User;
import com.junzhiit.nengji.model.enums.GoodsRefundStatus;
import com.junzhiit.nengji.model.enums.Is;

@Service
public class GoodsRefundServiceImpl implements GoodsRefundService{

	@Autowired
	private GoodsRefundDAO goodsRefundDAO;
	
	@Autowired
	private OrdersGoodsDAO ordersGoodsDAO;
	
	@Autowired
	private ShopDAO shopDAO;
	
	@Autowired
	private SystemUserCacheDAO systemUserCacheDAO;
	
	@Autowired
	private UserDAO userDAO;
	
	@Override
	public Map<String, Object> findAll(DataTablesParamVO dtp, GoodsRefundVO goodsRefundVO) {
		GoodsRefundBO goodsRefundBO = new GoodsRefundBO();
		BeanUtils.copyProperties(goodsRefundVO,goodsRefundBO);
		
		if (StringUtils.isBlank(goodsRefundVO.getShopId())) {
			SystemUserSessionVO systemUserSessionVO = systemUserCacheDAO
					.getHash(DIYKey.getSessionHashKey(goodsRefundVO.getSessionId()), SystemUserSessionVO.class);
			if(StringUtils.isNotBlank(systemUserSessionVO.getSystemId())){
				Shop shop = shopDAO.query(systemUserSessionVO.getSystemId());
//				Chain chain = chainDAO.query(systemUserSessionVO.getSystemId());
//				if (shop == null && chain == null) {
//					throw new ShopNotFoundException("店铺/品牌不存在");
//				}
				if (shop == null) {
					throw new ShopNotFoundException("店铺不存在");
				}
				if(shop != null){
					goodsRefundBO.setShopId(systemUserSessionVO.getSystemId());
//				}else if(chain != null){
//					ordersBO.setChainId(systemUserSessionVO.getSystemId());
				}
			}
		}
		
		List<GoodsRefundBO> list = goodsRefundDAO.findAll(goodsRefundBO, dtp.getStart(), dtp.getLength());
		int totalCount = goodsRefundDAO.getTotalCount(goodsRefundBO);
		
		return ViewObjectUtil.dataTables(list, dtp.getDraw(), totalCount);
	}

	@Override
	public ResultVO update(GoodsRefundVO goodsRefundVO) {
		ResultVO result = new ResultVO();
		GoodsRefund gr = goodsRefundDAO.query(goodsRefundVO.getId());
		OrdersGoods og = ordersGoodsDAO.query(gr.getOrdersGoodsId());
		gr.setStatus(goodsRefundVO.getStatus());
		Date now=new Date();
		
		if(goodsRefundVO.getStatus() == GoodsRefundStatus.AGREE.toIntStatus()){
			gr.setShopDealTime(now);		
			User user=userDAO.query(gr.getUserId());
			String mobilePhone=user.getMobilePhone();
			if(StringUtils.isNotBlank(mobilePhone)){
				SendPhoneMessageBO spmb=new SendPhoneMessageBO();
				spmb.setAuditFailDescription(SmsUtil.KEY_SEND_MOBLIE_PHONE);
				spmb.setMobilePhone(mobilePhone);
				spmb.setSmsModel(SmsUtil.GOODS_REFUND_AUDIT_SUCCESS);
				SmsUtil.sendPhoneMessage(spmb);
			}
		}
		if(goodsRefundVO.getStatus() == GoodsRefundStatus.REJECT.toIntStatus()){
			gr.setFailReason(goodsRefundVO.getFailReason());
			gr.setShopDealTime(now);
			gr.setCompleteTime(now);
			og.setIsRefundGoods(Is.NO.toIntValue());
			User user=userDAO.query(gr.getUserId());
			String mobilePhone=user.getMobilePhone();
			if(StringUtils.isNotBlank(mobilePhone)){
				SendPhoneMessageBO spmb=new SendPhoneMessageBO();
				spmb.setAuditFailDescription(SmsUtil.KEY_SEND_MOBLIE_PHONE);
				spmb.setMobilePhone(mobilePhone);
				spmb.setSmsModel(SmsUtil.GOODS_REFUND_AUDIT_FAIL);
				SmsUtil.sendPhoneMessage(spmb);
			}
		}
		if(goodsRefundVO.getStatus() == GoodsRefundStatus.COMPLETE.toIntStatus()){
			gr.setCompleteTime(now);
			og.setIsRefundGoods(Is.NO.toIntValue());
		}
		ordersGoodsDAO.update(og);
		goodsRefundDAO.update(gr);
		return result;
	}

	@Override
	public ResultVO findById(String ordersGoodsId) {
		ResultVO result = new ResultVO();
		GoodsRefundBO goodsRefundBO = goodsRefundDAO.findById(ordersGoodsId);
		result.setData(goodsRefundBO);
		return result;
	}

	@Override
	public ResultVO getApplyTotal(String sessionId) {
		ResultVO result = new ResultVO();
		SystemUserSessionVO systemUserSessionVO = systemUserCacheDAO
				.getHash(DIYKey.getSessionHashKey(sessionId), SystemUserSessionVO.class);
		
		Shop shop = shopDAO.query(systemUserSessionVO.getSystemId());
		if (shop == null) {
			throw new ShopNotFoundException("店铺不存在");
		}
		int count = goodsRefundDAO.getApplyTotal(shop.getId());
		result.setData(count);
		return result;
	}

	@Override
	public void updateGoodsRefundAgree() {
		List<GoodsRefund> grList=goodsRefundDAO.findAll();
		for(GoodsRefund gr:grList){
			if(gr.getShopDealTime()==null&&DateUtil.getDate(gr.getCreatedTime(),3).getTime()<new Date().getTime()){
				gr.setStatus(GoodsRefundStatus.AGREE.toIntStatus());
				gr.setShopDealTime(new Date());
				goodsRefundDAO.update(gr);
				User user=userDAO.query(gr.getUserId());
				String mobilePhone=user.getMobilePhone();
				if(StringUtils.isBlank(mobilePhone)){
					throw new MobilePhoneNotFoundException("电话号码不存在");
				}
				SMSParams sms=new SMSParams();
				sms.setParamKeys(new String[]{SmsUtil.KEY_SEND_MOBLIE_PHONE});
				sms.setPhoneNumbers(new String[]{mobilePhone});
				sms.setSignName(SmsUtil.ALIYUN_SMS_SIGN_NAME);
				sms.setTemplateCode(SmsUtil.GOODS_REFUND_AUDIT_SUCCESS);
				Boolean sendSuccess=false;
				try {
					SendSmsResponse response=SmsUtil.sendSms(sms);
					if(response.getCode()!=null&&("OK".equals(response.getCode()))){
						sendSuccess=true;
					}
					if(response.getCode()!=null&&SmsUtil.LIMIT_CONTROL_ERROR.equals(response.getCode())){
						throw new LimitControlException("不能过于频繁发送验证码,请稍后再发");
					}
				} catch (ClientException e) {
					e.printStackTrace();
				}
				if(!sendSuccess){
					throw new SendSMSFaileException("无法发送手机验证码");
				}
			}
		}
	}

	@Override
	public void updateGoodsRefundComplete() {
		List<GoodsRefund> grList=goodsRefundDAO.findAll();
		for(GoodsRefund gr:grList){
			if(DateUtil.getDate(gr.getShopDealTime(),7).getTime()<new Date().getTime()){
				gr.setStatus(GoodsRefundStatus.COMPLETE.toIntStatus());
				gr.setCompleteTime(new Date());
				goodsRefundDAO.update(gr);
			}
		}
	}
}
